package com.snifferx.util;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

@ManagedBean(name = "roleAccessDeniedHandler")
@RequestScoped
public class RoleAccessDeniedHandler implements AccessDeniedHandler {
	private String accessDeniedUrl;

	public RoleAccessDeniedHandler() {
	}

	public RoleAccessDeniedHandler(String accessDeniedUrl) {
		this.accessDeniedUrl = accessDeniedUrl;
	}

	@Override
	public void handle(HttpServletRequest request,
			HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException,
			ServletException {
		// perform redirect to obtain real URL in browser
		/*String webContext = request.getContextPath();
		String currentURL = request.getRequestURL().toString();		
		String pathWithinContext = currentURL.substring(currentURL.indexOf(webContext) + webContext.length());
		response.sendRedirect(pathWithinContext);*/
		
		
		response.sendRedirect(accessDeniedUrl);
		request.getSession().setAttribute("message",
				"You do not have permission to access this page!");

	}

	public String getAccessDeniedUrl() {
		return accessDeniedUrl;
	}

	public void setAccessDeniedUrl(String accessDeniedUrl) {
		this.accessDeniedUrl = accessDeniedUrl;
	}
}